import { Injectable } from '@angular/core';
import { Authority } from 'src/app/models';
import { BaseService } from '../../services/base.service';

@Injectable({
  providedIn: 'root'
})
export class AuthorityService extends BaseService {

  turnOn = false;
  /**
   * 超级查看权限
   */
  isSuperView = false;
  /**
   * 超级编辑权限
   */
  isSuperEdit = false;

  private _authorities: Authority[] = [];

  private _projectAuthorities: Authority[] = [];

  get authorities(): Authority[] {
    return this._authorities;
  }

  set authorities(auths: Authority[]) {
    this._authorities = auths;
  }

  get projectAuthorities(): Authority[] {
    return this._projectAuthorities;
  }

  set projectAuthorities(auths: Authority[]) {
    this._projectAuthorities = auths;
  }

  getUserAuthorities(params: {
    userId: string;
    accountId: string;
  }): Promise<Authority[]> {
    const url = `api/user/${params.userId}/account/${params.accountId}/accountpermits`;
    return this.get(url);
  }
  /**
   * 检测权限是否满足
   * @param data 组件在模板中的id和权限id
   */
  checkAuthority(data: {
    refObjectId: string;
    permitId?: string;
    refObjectType?: string;
    mode?: 'edit' | 'query' | 'export' | 'submit';
  }): boolean {
    if (!this.turnOn) {
      return true;
    }
    if (data.mode === 'edit' && this.isSuperEdit) {
      return true;
    }
    // 有编辑权限就能查看
    if (data.mode === 'query' && (this.isSuperView || this.isSuperEdit)) {
      return true;
    }
    const auths = this.filterAuthorities();
    if (auths && auths.length) {
      const existAuth = auths.find(auth => {
        const authPermitId = auth.permitId;
        let refIdResult = true;
        let permitIdResult = true;
        let typeResult = true;
        if (data.refObjectId) {
          refIdResult = data.refObjectId === auth.refObjectId;
        }
        if (data.permitId) {
          permitIdResult = data.permitId === authPermitId;
        }
        if (data.refObjectType) {
          typeResult = data.refObjectType === auth.refObjectType;
        }
        return refIdResult && permitIdResult && typeResult;
      });
      return !!existAuth;
    } else {
      return false;
    }
  }

  filterAuthorities() {
    let auths: Authority[] = [];
    if (this.projectAuthorities && this.projectAuthorities.length) {
      auths = this.projectAuthorities;
    } else if (this.authorities && this.authorities.length) {
      auths = this.authorities;
    }
    return auths;
  }

}
